<template>
  <view>

  </view>
</template>

<script>
  export default {
    name: "role-authority-popup",
    props: {
      pageType: {
        type: String,
        default: 'detail'
      },
      roleNo: {
        type: String,
        default: ''
      },
      nodeKey: {
        type: String,
        default: 'fun_no'
      },
      nodeKey: {
        type: String,
        default: 'fun_name'
      }
    },
    data() {
      return {
        loading: false,
        roleModel: {
          remark: "",
          role_name: ""
        },
        roleData: null, // 回显角色信息
        roleFunData: null, // 默认角色权限合计。
        treeData: [],
        defaultExpandAll: true,
        defaultProps: [],
        checkedKeys: [],
        expandedKeys: [],
        terminalType: [],
        buildData: [],
        terminalTypeModel: null,
        data: [{
          "role_name": "内部角色1",
          "type": "add",
          "role_no": "角色编号",
          "remark": "说明",
          "menus": ["test_menu"],
          "funs": ["001", "002"],
          "srvs": [{
            "service": "srvtest_table_select",
            "operate_type": "select"
          }]
        }],
        authFunListdata: [],
        checkedNodes: [],
        req: {
          "role_name": "内部角色1",
          "type": "add",
          "role_no": "角色编号",
          "remark": "说明",
          "menus": ["test_menu"],
          "funs": ["001", "002"],
          "srvs": [{
            "service": "srvtest_table_select",
            "operate_type": "select"
          }]
        },
      };
    },
    methods: {

      onSubmit() {
        this.loading = true
        if (this.pageType == 'update') {
          this.setRoleAuth()
        } else if (this.pageType == 'add') {
          this.setRoleAuth()
        } else if (this.pageType == 'detail') {
          this.loadUpdateDefaultData()
        }

      },
      reqRun() {
        // let nodes = this.checkedNodes
        let req = {
          "role_name": this.roleModel.role_name,
          "type": this.pageType,
          "remark": this.roleModel.remark,
          "menus": [],
          "funs": [],
          "srvs": []
        }
        let checkedNodes = []
        let trees = this.terminalType
        for (let node in trees) {
          let nodes = []
          let treemode = 'tree' + node
          nodes = this.$refs[treemode][0].store._getAllNodes()
          //  checkedNodes = nodes.filter((item) => item.checked == true)
          for (let nl of nodes) {
            if (nl.checked == true) {
              checkedNodes.push(nl)
            }
          }
          //  checkedNodes = checkedNodes.concat(nodes)
        }
        for (let n in checkedNodes) {
          if (checkedNodes[n].data.relate_menu_no) {
            req.menus.push(checkedNodes[n].data.relate_menu_no)
          }
          if (checkedNodes[n].data.fun_no) {
            req.funs.push(checkedNodes[n].data.fun_no)
          }
          let srv = {
            "service": "srvtest_table_select",
            "operate_type": "select"
          }
          if (checkedNodes[n].data.relate_srv) {
            srv = {
              "service": checkedNodes[n].data.relate_srv,
              "operate_type": checkedNodes[n].data.srv_type
            }
            req.srvs.push(JSON.stringify(srv))
          }
        }
        req.funs = Array.from(new Set(req.funs))
        req.menus = Array.from(new Set(req.menus))
        req.srvs = Array.from(new Set(req.srvs))
        let arr = req.srvs
        req.srvs = arr.map((item) => JSON.parse(item))
        // let srvsStr = JSON.stringify(req.srvs)

        if (this.pageType == 'update') {
          req.role_no = this.roleNo
        }

        return [{
          "serviceName": "srvsys_set_app_role_auth",
          "srvApp": "retail",
          "data": [req]
        }]
      },
      onChange(e) {
        console.log('on-select', e);
      },
      checkChange(e, item, index) {
        console.log(...arguments);
        debugger
        let tree = 'tree' + index
        let allKeys = this.authFunListdata.map((item) => {
          return item[this.nodeKey]
        })
        let allNodes = this.$refs[tree][0].store._getAllNodes()
        if (index === 0) {
          if (e.value == 'checked') {
            if (e.checked) {
              this.$refs.tree0[0].setCheckedKeys(allKeys)
              this.checkedNodes = allNodes.map((item) => item.data)
            } else {
              this.$refs.tree0[0].setCheckedKeys([])
              let checkNodes = []
              this.checkedNodes = checkNodes.map((item) => item)
            }
          }
        } else if (index === 1) {
          if (e.value == 'checked') {
            if (e.checked) {
              this.$refs.tree1[0].setCheckedKeys(allKeys)
            } else {
              this.$refs.tree1[0].setCheckedKeys([])
            }
          }
        }

        if (e.value == 'expand') {
          let isExpand = e.checked
          console.log(allNodes, this.$refs.tree0[0])
          allNodes = allNodes.map((item) => {
            item['expanded'] = isExpand
            return item
          })
        }
        // let ref = this.$refs[tree]
        // item._treeData = item._treeData.map((item) => item)
        this.$forceUpdate()
      },
      treeCurrentChange(checkedNodes, checkedKeys) {
        let nodes = checkedKeys.checkedNodes
        this.checkedNodes = nodes.map((item) => item)

        //  console.log('treeCurrentChange',checkedKeys.checkedNodes)
      },
      loadUpdateDefaultData() {
        let req = {
          "serviceName": "srvsys_app_role_fun_select",
          "colNames": [
            "*"
          ],
          "condition": [{
            "colName": "role_no",
            "ruleType": "in",
            "value": this.roleNo
          }]
        }
        const url = `/retail/select/srvsys_app_role_fun_select`
        this.getRoleDetail()
        this.$http.post(url, req).then((res) => {
          console.log("loadUpdateDefaultData", res.data)
          //
          this.roleFunData = res.data.data
        })

      },
      getRoleDetail() {
        // 查找角色信息
        const url = `/retail/select/srvsys_app_role_select`
        const req = {
          "serviceName": "srvsys_app_role_select",
          "colNames": [
            "*"
          ],
          "condition": [{
            "colName": "role_no",
            "ruleType": "in",
            "value": this.roleNo
          }]
        }
        this.$http.post(url, req).then((res) => {
          console.log("getRoleDetail", res.data)
          this.roleData = res.data.data
          this.roleModel.role_name = this.roleData && this.roleData.length > 0 ? this.roleData[0].role_name : ""
          this.roleModel.remark = this.roleData && this.roleData.length > 0 ? this.roleData[0].remark : ""
        })
      },
      setRoleAuth() {
        // 保存权限设置请求
        let req = this.reqRun()
        console.log('setRoleAuth', req)
        const url = `/retail/operate/setRoleAuth`
        this.$http.post(url, req).then((res) => {
          console.log('setRoleAuth', res)
          this.loading = false
          if (res.data.state == "SUCCESS" && res.data.resultCode == "SUCCESS") {
            uni.showToast({
              title: res.data.response[0].response.msg,
              icon: "success"
            })
            let role_no = res.data.response[0].response.role_no
            if (this.pageType == 'add') {
              // this.$router.push({
              //   name: "authorityPage",
              //   params: {
              //     type: 'update',
              //     role_no: role_no
              //   }
              // })
            } else if (this.pageType == 'update') {
              this.loadUpdateDefaultData()
            }

          } else {
            uni.showToast({
              title: res.data.resultMessage,
              icon: "none"
            })
          }
        })
      },
      handleCheckedCitiesChange(e) {
        console.log("handleCheckedCitiesChange", e)
      },
      onClick(e) {
        this.getDefaultTreeData()
      },
      getTreeData() {
        let serviceName = "srvsys_fun_auth_def_select"
        const url = `/retail/select/srvsys_fun_auth_def_select`
        let cond = []
        let req = {
          "serviceName": serviceName,
          "colNames": [
            "*"
          ],
        }
        this.$http.post(url, req).then((res) => {
          console.log(res.data)
          this.authFunListdata = res.data.data
          this.generateOptions(this.authFunListdata)
        })
      },
      getUserChecked(cfg, key) {
        let isChecked = false
        for (let val of cfg) {
          if (val.value == key) {
            isChecked = val.checked
          }
        }
        return isChecked
      },
      // 开始递归方法
      generateOptions(params, checked, expand) {
        let type = this.terminalType
        for (let t of type) {
          var result = []
          let list = params.filter(item => item.terminal_type == t.terminal_type)
          for (const param of list) {
            if (param.parent_no == null || param.parent_no == '' || param.parent_no == undefined) { // 判断是否为顶层节点
              let children = this.deepClone(param)
              children['label'] = children[this.nodeLabel]
              children['children'] = this.getchilds(children[this.nodeKey], list) // 获取子节点
              result.push(children)
            }
          }
          this.$set(t, '_treeData', result.map((item) => item))
          //t['_treeData'] = result.map((item) => item)
          t['expandedKeys'] = []
          t['checkStrictly'] = false
          t['checkedKeys'] = []
          // update 根据编号递归 特类型的选中项
          if (this.pageType == 'update') {
            for (let funCol of this.authFunListdata) {
              for (let checkNode of this.roleFunData) {
                if (funCol[this.nodeKey] == checkNode[this.nodeKey] && t.terminal_type == funCol['terminal_type']) {
                  t.checkedKeys.push(checkNode[this.nodeKey])
                }
              }
            }
          }
        }
        this.loading = false
      },

      getchilds(nodeKey, array) {
        const childs = []
        for (const arr of array) { // 循环获取子节点
          if (arr['parent_no'] === nodeKey) {
            childs.push(this.deepClone(arr))
          }
        }
        for (const child of childs) { // 获取子节点的子节点
          const childscopy = this.getchilds(child[this.nodeKey], array) // 递归获取子节点

          child['label'] = child[this.nodeLabel]
          child['children'] = childscopy
        }
        return childs
      },

      getDefaultTreeData() {
        let serviceName = "srvsys_fun_auth_def_select"

        const url = `/retail/select/${serviceName}`
        const req = {
          "serviceName": serviceName,
          "colNames": [
            "*"
          ],
          group: [{
            "colName": "terminal_type",
            "type": "by"
          }]
        }
        this.$http.post(url, req).then((res) => {
          console.log(res.data)
          let types = res.data.data
          this.terminalType = types.map((item) => {
            item['value'] = []
            //折叠/展开"  全选/全不选  父子联动 
            item['checkCfg'] = [{
              label: "折叠/展开",
              value: "expand",
              checked: true
            }, {
              label: "全选/全不选",
              value: "checked",
              checked: false
            }, {
              label: "父子联动",
              value: "cascade",
              checked: false
            }]
            return item
          })
          this.getTreeData()
        })
      }

    },
    created() {
      this.loading = true
      if (this.pageType == 'update') {
        this.loadUpdateDefaultData()
      } else if (this.pageType == 'add') {

      } else if (this.pageType == 'detail') {
        this.loadUpdateDefaultData()
      }
      this.getDefaultTreeData()
    }
  }
</script>

<style>

</style>
